import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-18
 * Time: 17:30
 */
public class TCPEchoClient {
    private final Socket socket;
    //
    public TCPEchoClient(String severIp,int port) throws IOException {
        socket = new Socket(severIp,port);
    }
    //
    public void start(){
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //读取控制台
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetWork = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){
                System.out.print("->");
                //在用户输入之前，hasNext()有阻塞效果
                if (!scannerConsole.hasNext()){
                    break;
                }
                //1.从控制台输入请求
                String request = scannerConsole.next();
                //2.发送请求
                //让请求的结尾有\n
                printWriter.println(request);
                //刷新缓冲区
                printWriter.flush();
                //3.从服务器读取响应
                String response = scannerNetWork.next();
                //4.将响应打印到控制台
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //
    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
